package com.whfc.fim.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.AppWarnModuleType;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.fim.dao.FimAlgResultImgMapper;
import com.whfc.fim.dao.FimAlgResultMapper;
import com.whfc.fim.dto.FimMsgToUserDTO;
import com.whfc.fim.dto.FimResultWarnDTO;
import com.whfc.fim.entity.FimAlgResult;
import com.whfc.fim.enums.FimDeviceRuleType;
import com.whfc.fim.manager.FimResultManager;
import com.whfc.fim.param.FimAlgResultParam;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Description 监控演示数据
 * @Author hw
 * @Date 2021-09-10 11:50
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class FimDataDemoJob {


    @Autowired
    private FimResultManager fimResultManager;

    @Autowired
    private FimAlgResultImgMapper fimAlgResultImgMapper;

    @Autowired
    private FimAlgResultMapper fimAlgResultMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final String CONTENT = "%s在%s,监测到%s,请您及时处理";

    @XxlJob("fimDataDemo")
    public void fimDataDemo() {
        try {
            String paramStr = XxlJobHelper.getJobParam();
            if (StringUtils.isEmpty(paramStr)) {
                XxlJobHelper.handleSuccess("没有配置对应的请求参数");
                return;
            }
            XxlJobHelper.log("请求参数为：{}", paramStr);
            JSONObject param = JSONObject.parseObject(paramStr);
            List<Integer> deptIds = null;
            List<Integer> checkTypes = null;
            Integer deviceId = 0;
            String deviceName = null;
            if (param.containsKey("deptIds")) {
                deptIds = param.getJSONArray("deptIds").toJavaList(Integer.class);
            }
            if (deptIds == null) {
                XxlJobHelper.handleSuccess("没有配置deptIds参数");
                return;
            }
            if (param.containsKey("checkTypes")) {
                checkTypes = param.getJSONArray("checkTypes").toJavaList(Integer.class);
            }
            if (param.containsKey("deviceId")) {
                deviceId = param.getInteger("deviceId");
            }
            if (param.containsKey("deviceName")) {
                deviceName = param.getString("deviceName");
            }
            if (StringUtils.isEmpty(deviceName)) {
                deviceName = "萤石云-P30-DVR";
            }
            List<Date> times = new ArrayList<>();
            if (param.containsKey("startTime") && param.containsKey("endTime")) {
                Date startTime = param.getDate("startTime");
                Date startDate = DateUtil.getDateBegin(startTime);
                Date endTime = param.getDate("endTime");
                Date endDate = DateUtil.getDateEnd(endTime);
                times = DateUtil.getDayListOfMinute(startDate, endDate, 60);
            } else {
                times.add(new Date());
            }
            //三分之一的几率生成数据
            Random random = new Random();
            for(Date date : times) {
                int i = random.nextInt(3);
                if (i != 0) {
                    XxlJobHelper.log("几率不对！这次就不生成了");
                    continue;
                }
                for (Integer deptId : deptIds) {
                    FimAlgResult fimAlgResult = fimAlgResultMapper.getRandomWarnRule(checkTypes);
                    List<String> list = fimAlgResultImgMapper.selectImgUrlByResultId(fimAlgResult.getId());
                    FimAlgResultParam fimAlgResultParam = new FimAlgResultParam();
                    fimAlgResultParam.setAlgCheckType(fimAlgResult.getAlgCheckType());
                    fimAlgResultParam.setAlgCheckTypeName(fimAlgResult.getAlgCheckTypeName());
                    fimAlgResultParam.setAlgResultImgList(list);
                    fimAlgResultParam.setDeptId(deptId);
                    fimAlgResultParam.setDeviceId(deviceId);
                    fimAlgResultParam.setDeviceName(deviceName);
                    fimAlgResultParam.setDeviceVendor("萤石云");
                    fimAlgResultParam.setTime(DateUtil.addSeconds(date, -random.nextInt(3600)));
                    FimResultWarnDTO fimResultWarnDTO = fimResultManager.uploadAlgResult(fimAlgResultParam);

                    Integer resultId = fimResultWarnDTO.getResultId();
                    Integer algCheckType = fimResultWarnDTO.getAlgCheckType();
                    Date time = fimResultWarnDTO.getTime();
                    List<FimMsgToUserDTO> userDtoList = fimResultWarnDTO.getUserDtoList();
                    List<Integer> msgChannelList = fimResultWarnDTO.getMsgChannelList();
                    // 生成报警消息
                    List<AppMsgToUserDTO> msgToUserDTOS = transferData(userDtoList);
                    this.generateMessage(resultId, deptId, deviceName, algCheckType, time, msgToUserDTOS, msgChannelList);
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 转换消息接收人
     *
     * @param userDtoList 消息接收人
     * @return 消息接收人
     */
    private List<AppMsgToUserDTO> transferData(List<FimMsgToUserDTO> userDtoList) {
        List<AppMsgToUserDTO> list = new ArrayList<>();
        if (userDtoList == null || userDtoList.isEmpty()) {
            return list;
        }
        for (FimMsgToUserDTO fimMsgToUserDTO : userDtoList) {
            AppMsgToUserDTO appMsgToUserDTO = new AppMsgToUserDTO();
            appMsgToUserDTO.setDeptId(fimMsgToUserDTO.getDeptId());
            appMsgToUserDTO.setDeptName(fimMsgToUserDTO.getDeptName());
            appMsgToUserDTO.setUserId(fimMsgToUserDTO.getUserId());
            appMsgToUserDTO.setUsername(fimMsgToUserDTO.getUsername());
            appMsgToUserDTO.setNickName(fimMsgToUserDTO.getNickName());
            appMsgToUserDTO.setPhone(fimMsgToUserDTO.getPhone());
            appMsgToUserDTO.setRuleId(fimMsgToUserDTO.getRuleId());
            list.add(appMsgToUserDTO);
        }
        return list;
    }

    /**
     * 生成报警消息
     *
     * @param resultId     记录ID
     * @param deptId       组织机构ID
     * @param deviceName   设备名称
     * @param algCheckType 报警类型
     * @param time         触发时间
     */
    private void generateMessage(Integer resultId,
                                 Integer deptId,
                                 String deviceName,
                                 Integer algCheckType,
                                 Date time,
                                 List<AppMsgToUserDTO> userDtoList,
                                 List<Integer> msgChannelList) {
        FimDeviceRuleType fimDeviceRuleType = FimDeviceRuleType.parseByValue(algCheckType);
        String tittle = fimDeviceRuleType.tittle();
        String desc = fimDeviceRuleType.detail();
        String content = String.format(CONTENT, deviceName, DateUtil.formatDateTime(time), desc);

        PushMsgDTO msgDTO = new PushMsgDTO();
        msgDTO.setDeptId(deptId);
        msgDTO.setModuleType(AppWarnModuleType.FIM.value());
        msgDTO.setTime(time);
        msgDTO.setMsgObjectId(String.valueOf(resultId));
        msgDTO.setTitle(tittle);
        msgDTO.setContent(content);
        msgDTO.setToUserList(userDtoList);
        msgDTO.setMsgChannelList(msgChannelList);

        amqpTemplate.convertAndSend(QueueConst.PUSH_MSG_EXCHANGE, "", JSONUtil.toString(msgDTO));
    }

}
